package com.lyn.plugin.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author Lyn
 * @date 2022/5/22
 * @desc 日志工具类
 */
public class LogUtil {

    private static boolean isDebugVersions = true;


    public final static StringBuilder stringBuilder = new StringBuilder();

    public static void d(String msg) {
        if (!isDebugVersions) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            Log.e(getTag(getStackTraceElement()), "null");
            return;
        }
        Log.d(getTag(getStackTraceElement()), msg);
    }

    public static void i(String msg) {
        if (!isDebugVersions) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            Log.e(getTag(getStackTraceElement()), "null");
            return;
        }
        Log.i(getTag(getStackTraceElement()), msg);
    }

    public static void w(String msg) {
        if (!isDebugVersions) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            Log.e(getTag(getStackTraceElement()), "null");
            return;
        }
        Log.w(getTag(getStackTraceElement()), msg);
    }

    public static void e(String msg) {
        if (!isDebugVersions) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            Log.e(getTag(getStackTraceElement()), "null");
            return;
        }
        Log.e(getTag(getStackTraceElement()), msg);
    }

    /**
     * 获取运行堆栈
     *
     * @return 堆栈
     */
    public static StackTraceElement getStackTraceElement() {
        StackTraceElement[] stackTrace = new Throwable().getStackTrace();
        return stackTrace[2];
    }

    public static String getTag(StackTraceElement element) {
        if (stringBuilder.length() > 0) {
            stringBuilder.delete(0, stringBuilder.length());
        }
        stringBuilder.append("(");
        stringBuilder.append(element.getFileName());
        stringBuilder.append(":");
        stringBuilder.append(element.getLineNumber());
        stringBuilder.append(")");
        return stringBuilder.toString();
    }

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            isDebugVersions = (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
            return isDebugVersions;
        } catch (Exception e) {
            isDebugVersions = false;
            return false;
        }
    }


}
